$(function(){

  $.navClickListener = function(oid, name){
    // do nothing here
  };

  $.onNavClicked = function (fn) {
    $.navClickListener = fn;
  };

  function levelToClass(x) {
    if (x === 1) return 'level-1';
    if (x === 2) return 'level-2';
    if (x === 3) return 'level-3';
  }

  function classRender(clist, level){
    var result = '';
    for (var i = 0; i < clist.length; ++i){
      var li_class = 'close-item';
      var sub_item ='';
      if (clist[i]['children'].length !== 0) {
        li_class = 'has-child-item close-item';
        sub_item = '<ul class="nav child-nav ' + levelToClass(level) + '">'
          + classRender(clist[i]['children'], level + 1)
          + '</ul>';
      }
      var class_id = clist[i]['id'];
      var class_name = clist[i]['name'];
      result += ('<li class="' + li_class + '">'
        + '<a href="javascript:$.navClickListener(\''
        + class_id + '\', \'' + class_name + '\')">'
        + (level <= 1? '<i class="fa fa-cubes" aria-hidden="true"></i>' : '')
        + '<span>'+ class_name+'</span>'
        + '</a>'
        +  sub_item
        + '</li>'
      );
    }
    return result;
  }

  $.get(Urls.resolve('storage_api_v1:material_category_tree'), '', function(data, textStatus, jqXHR){
    $("#main-nav").append($.parseHTML(classRender(data['data'], 1)));
  });
});